package de.tewdreyer.android.erc;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class HttpPoster {
	private String      url;
	private HttpEntity  entity;
	private int         errorCode = -1;

	/**
	 * accessor for errorCode
	 * @return errorCode is -1, means internal error
	 */
	public int ErrorCode(){
		return errorCode;
	}
	
	/**
	 * create a new httpPoster object
	 * @param url url where to post the entity
	 * @param entity  entity that will be sent
	 */
	public HttpPoster(String url, HttpEntity entity) {
		this.url = url;
		this.entity = entity;
	}
	
	/**
	 * perform a http post by sending a given entity to a given url
	 * @return statusCode status of http post
	 * @return errorCode  -1 on internal failure
	 */
	public int performPost() {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		HttpResponse response;
/
		if(entity == null)
			return errorCode;

		httpPost.setEntity(entity);

		try {
			response = httpClient.execute(httpPost);
		} catch (IOException e){
			return errorCode;
		}

		if(response == null)
			return errorCode;

		StatusLine statusLine = response.getStatusLine();

		if(statusLine == null)
			return errorCode;

		return statusLine.getStatusCode();
	}

	/**
	 * create a multipart stringbody element
	 * @param  string     string that should be added to a multipart entity
	 * @return stringBody stringbody element that could be added to a multipart entity
	 */
	public static StringBody createStringBody(String string) {
		StringBody stringBody = null;
		try {
			stringBody = new StringBody(string);
		} catch (UnsupportedEncodingException e) {
			stringBody = null;
		}
		return stringBody;
	}
}
